package com.liang.paul.officelite.adapters;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dd.processbutton.iml.ActionProcessButton;
import com.liang.paul.officelite.R;
import com.liang.paul.officelite.beams.FileBeam;

import java.io.File;
import java.util.ArrayList;

import cn.bmob.v3.listener.DownloadFileListener;

/**
 * Created by paulliang on 16/5/30.
 */
public class FileAdpter extends BaseAdapter {

    ArrayList<FileBeam> datas;
    Context context;

    public FileAdpter(ArrayList<FileBeam> datas, Context context) {
        this.datas = datas;
        this.context = context;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.list_file, null);
        }
        TextView name = (TextView) convertView.findViewById(R.id.txt_file_name);
        final TextView date = (TextView) convertView.findViewById(R.id.txt_file_date);
        final ActionProcessButton btn_downlod = (ActionProcessButton) convertView.findViewById(R.id.btn_file_download);
        name.setText(datas.get(position).getFile().getFilename());
        date.setText("文件上传于: " + datas.get(position).getCreatedAt());
        if(isFileExists(datas.get(position))){
            btn_downlod.setProgress(100);
        }
        final int pos = position;
        btn_downlod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(Environment.getExternalStorageDirectory(),
                        "officelite" + "/" + datas.get(pos).getTeamId() + "/" + datas.get(pos).getFile().getFilename());
                if(isFileExists(datas.get(pos))){
                    openFile(file);
                }else {
                    datas.get(pos).getFile().download(context, file, new DownloadFileListener() {

                        @Override
                        public void onStart() {
                            btn_downlod.setProgress(0);
                            btn_downlod.setClickable(false);
                        }

                        @Override
                        public void onProgress(Integer progress, long total) {
                            btn_downlod.setProgress(progress);
                        }

                        @Override
                        public void onSuccess(String s) {
                            btn_downlod.setProgress(100);
                            btn_downlod.setClickable(true);
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            btn_downlod.setProgress(0);
                            Toast.makeText(context, "下载失败-->" + s, Toast.LENGTH_SHORT).show();
                            btn_downlod.setClickable(true);
                        }
                    });
                }
            }
        });

        return convertView;
    }

    private boolean isFileExists(FileBeam beam){
        try{
            File file = new File(Environment.getExternalStorageDirectory(),
                    "officelite" + "/" + beam.getTeamId() + "/" + beam.getFile().getFilename());
            if(!file.exists())
                return false;
        }catch (Exception e){
            return false;
        }

        return true;
    }

    private String getMIMEType(File file)
    {
        String type="*/*";
        String fName=file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if(dotIndex < 0){
            return type;
        }
        String end=fName.substring(dotIndex,fName.length()).toLowerCase();
        if(end=="")return type;
        for(int i=0;i<MIME_MapTable.length;i++){
            if(end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private void openFile(File file){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        context.startActivity(intent);
    }




    private final String[][] MIME_MapTable={
            //{后缀名，    MIME类型}
            {".3gp",    "video/3gpp"},
            {".apk",    "application/vnd.android.package-archive"},
            {".asf",    "video/x-ms-asf"},
            {".avi",    "video/x-msvideo"},
            {".bin",    "application/octet-stream"},
            {".bmp",      "image/bmp"},
            {".c",        "text/plain"},
            {".class",    "application/octet-stream"},
            {".conf",    "text/plain"},
            {".cpp",    "text/plain"},
            {".doc",    "application/msword"},
            {".exe",    "application/octet-stream"},
            {".gif",    "image/gif"},
            {".gtar",    "application/x-gtar"},
            {".gz",        "application/x-gzip"},
            {".h",        "text/plain"},
            {".htm",    "text/html"},
            {".html",    "text/html"},
            {".jar",    "application/java-archive"},
            {".java",    "text/plain"},
            {".jpeg",    "image/jpeg"},
            {".jpg",    "image/jpeg"},
            {".js",        "application/x-javascript"},
            {".log",    "text/plain"},
            {".m3u",    "audio/x-mpegurl"},
            {".m4a",    "audio/mp4a-latm"},
            {".m4b",    "audio/mp4a-latm"},
            {".m4p",    "audio/mp4a-latm"},
            {".m4u",    "video/vnd.mpegurl"},
            {".m4v",    "video/x-m4v"},
            {".mov",    "video/quicktime"},
            {".mp2",    "audio/x-mpeg"},
            {".mp3",    "audio/x-mpeg"},
            {".mp4",    "video/mp4"},
            {".mpc",    "application/vnd.mpohun.certificate"},
            {".mpe",    "video/mpeg"},
            {".mpeg",    "video/mpeg"},
            {".mpg",    "video/mpeg"},
            {".mpg4",    "video/mp4"},
            {".mpga",    "audio/mpeg"},
            {".msg",    "application/vnd.ms-outlook"},
            {".ogg",    "audio/ogg"},
            {".pdf",    "application/pdf"},
            {".png",    "image/png"},
            {".pps",    "application/vnd.ms-powerpoint"},
            {".ppt",    "application/vnd.ms-powerpoint"},
            {".prop",    "text/plain"},
            {".rar",    "application/x-rar-compressed"},
            {".rc",        "text/plain"},
            {".rmvb",    "audio/x-pn-realaudio"},
            {".rtf",    "application/rtf"},
            {".sh",        "text/plain"},
            {".tar",    "application/x-tar"},
            {".tgz",    "application/x-compressed"},
            {".txt",    "text/plain"},
            {".wav",    "audio/x-wav"},
            {".wma",    "audio/x-ms-wma"},
            {".wmv",    "audio/x-ms-wmv"},
            {".wps",    "application/vnd.ms-works"},
            //{".xml",    "text/xml"},
            {".xml",    "text/plain"},
            {".z",        "application/x-compress"},
            {".zip",    "application/zip"},
            {"",        "*/*"}
    };
}
